#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
#include <ctime>
#include "RingQueue.hpp"
#include "Task.hpp"

using namespace std;

struct ThreadData
{
    RingQueue<Task>* rq;
    string threadname;
};

void *Productor(void *args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    RingQueue<Task>* rq = td->rq;
    string name = td->threadname;

    while (true)
    {
        // 1、获取数据
        int data1 = rand() % 10 + 1;
        usleep(10);
        int data2 = rand() % 10;
        char oper = opers[rand() % opers.size()];
        Task t(data1, data2, oper);

        // 2、生产数据
        rq->Push(t);
        cout << "Productor task done, task is: " << t.GetTask() << " who: " << name << endl;
        sleep(1);
    }
}

void *Consumer(void *args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    RingQueue<Task>* rq = td->rq;
    string name = td->threadname;

    while (true)
    {
        // 1、获取数据
        Task t;
        rq->Pop(&t);

        // 2、处理数据
        t();
        cout << "Consumer get a task: " << t.GetTask() << " who: " << name 
            << " result:" << t.GetResult() << endl;
        sleep(1);
    }
}

int main()
{
    srand((unsigned int)time(nullptr) ^ getpid());
    RingQueue<Task> *rq = new RingQueue<Task>();
    pthread_t c[3], p[5];

    for (int i = 1; i <= 5; i++)
    {
        ThreadData* td = new ThreadData();
        td->rq = rq;
        td->threadname = "Productor-" + to_string(i);

        pthread_create(p + i, nullptr, Productor, td);
    }

    for (int i = 1; i <= 5; i++)
    {
        ThreadData* td = new ThreadData();
        td->rq = rq;
        td->threadname = "Consumer-" + to_string(i);

        pthread_create(c + i, nullptr, Consumer, td);
    }
    
    for (int i = 1; i <= 5; i++)
    {
        pthread_join(p[i], nullptr);
    }

    for (int i = 1; i <= 5; i++)
    {
        pthread_join(c[i], nullptr);
    } 

    return 0;
}